package com.github.hongkaiwen.rxjava.play.problem1;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.reactivex.Observable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class FutureSolve extends Base {


    public static void main(String... args) {
        ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("worker-%d").setDaemon(true).build();
        ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 3,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(), factory);

        FutureSolve futureSolve = new FutureSolve();

        Future<Integer> f1 = pool.submit(() -> futureSolve.a());
        Future<Integer> f2 = pool.submit(() -> futureSolve.b());
        Future<Integer> f3 = pool.submit(() -> futureSolve.c());

        Observable.merge(Observable.fromFuture(f1), Observable.fromFuture(f2), Observable.fromFuture(f3))
            .reduce((i, j) -> {
                System.out.println("reduce runs on: " + Thread.currentThread().getName());
                return i + j;
            })
            .subscribe(futureSolve::result);
    }

}
